import numpy as np
import math
import torch


def fre_statis(fc1_w, fc2_w, fc3_w, fc4):
    fc4_imp = np.zeros(2)
    fc3_imp = np.zeros(16)
    fc2_imp = np.zeros(32)
    fc1_imp = np.zeros(64 * 291)
    imp = torch.zeros(fc4.shape[0], 291)
    imp_idx = torch.zeros(fc4.shape[0], 291)
    z = 0
    for kk in range(fc4.shape[0]):
        print("num:", kk)
        temp = fc4[kk]
        if temp[1] > temp[0]:
            fc4_imp[0] = (math.exp(temp[0]) * math.exp(temp[1])) / (
                    (math.exp(temp[0]) + math.exp(temp[1])) * (math.exp(temp[0]) + math.exp(temp[1])))
            fc4_imp[1] = 0
            # 得到第四层2个神经元的值

            for i in range(0, 16):
                fc3_imp[i] = 0
                for j in range(0, 2):
                    fc3_imp[i] = fc3_imp[i] + fc3_w[j][i] * fc4_imp[j]
            # 得到第三层16个神经元的值

            for i in range(0, 32):
                fc2_imp[i] = 0
                for j in range(0, 16):
                    fc2_imp[i] = fc2_imp[i] + fc2_w[j][i] * fc3_imp[j]
            # 得到第二层32个神经元的值

            for i in range(0, 291 * 64):
                fc1_imp[i] = 0
                for j in range(0, 32):
                    fc1_imp[i] = fc1_imp[i] + fc1_w[j][i] * fc2_imp[j]

            H = np.zeros(291)
            for i in range(0, 291):
                for j in range(64 * i, 64 * (i + 1)):
                    H[i] = H[i] + fc1_imp[j]
        else:
            fc4_imp[1] = (math.exp(temp[0]) * math.exp(temp[1])) / (
                    (math.exp(temp[0]) + math.exp(temp[1])) * (math.exp(temp[0]) + math.exp(temp[1])))
            fc4_imp[0] = 0

            for i in range(0, 16):
                fc3_imp[i] = 0
                for j in range(0, 2):
                    fc3_imp[i] = fc3_imp[i] + fc3_w[j][i] * fc4_imp[j]

            for i in range(0, 32):
                fc2_imp[i] = 0
                for j in range(0, 16):
                    fc2_imp[i] = fc2_imp[i] + fc2_w[j][i] * fc3_imp[j]

            for i in range(0, 291 * 64):
                fc1_imp[i] = 0
                for j in range(0, 32):
                    fc1_imp[i] = fc1_imp[i] + fc1_w[j][i] * fc2_imp[j]

            H = np.zeros(291)
            for i in range(0, 291):
                for j in range(64 * i, 64 * (i + 1)):
                    H[i] = H[i] + fc1_imp[j]

        B = np.argsort(H)
        B = list(reversed(B))  # B中存储排序后的下标
        A = sorted(H, reverse=True)  # A中存储排序后的结果
        AA = torch.tensor(A)
        BB = torch.tensor(B)
        imp[z] = AA
        imp_idx[z] = BB
        z += 1
    # 提取每个人特征排序
    best_imp = imp
    best_idx = imp_idx

    return best_imp, best_idx
